#coding:utf-8

import pygame
import requests
from aip import AipSpeech
from Record import record
from Config import config as cf


# parameter
APP_ID = cf.APP_ID1
API_KEY = cf.API_KEY1
SECRET_KEY = cf.SECRET_KEY1
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


def speech_recognition(filePath):
    voiceType = filePath.split('.')[-1]
    with open(filePath, 'rb') as fp:
        voice = fp.read()
    try:
        results = client.asr(voice, voiceType, 16000, {
            'dev_pid': 1536,
        })
        return results['result'][0]
    except:
        return ' '


def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : cf.API_KEY2,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return "没听懂 能再说一遍吗"


def speech_synthesis(text):
    results  = client.synthesis(text, 'zh', 1, {
        'vol': 5,
        'pre':0
    })
    if not isinstance(results, dict):
        with open('temp/auido.mp3', 'wb') as f:
            f.write(results)
    pygame.mixer.init()
    track = pygame.mixer.music.load('temp/auido.mp3')
    pygame.mixer.music.play()


record.recording()
voiceWord = speech_recognition('temp/my_say_voice.pcm')
print(voiceWord)
answer = get_response(voiceWord)
print(answer)
if '喜欢谁' in voiceWord:
    answer = '当然是我家露儿呀'
speech_synthesis(answer)


